package com.joinway.framework.admin.core.plugin.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.joinway.framework.admin.core.service.table.TableService;
import com.joinway.framework.bean.view.View;
import com.joinway.framework.core.repository.FrameworkRepository;
import com.joinway.framework.core.utils.AppEnv;

@Service
public class SystemConfigTableService extends TableService {

	@Autowired protected FrameworkRepository repo;
	
	@Override
	public String getTableName() {
		return "systemConfig";
	}

	@Override
	protected String getFindAllSql(String tableName) {
		String[] targets = getTargetAppIds();
		String appIds = "'" + StringUtils.join(targets, "','") + "'";
		
		return "select * from system_config where app_id in (" + appIds + ")";
	}

	protected String[] getTargetAppIds(){
		return new String[]{AppEnv.getAppId()};
	}

	@Override
	public View save(String table, String idField, Map<String, String> params) throws Exception {
		View view = super.save(table, idField, params);
		
		repo.clearSystemConfig();
		
		return view;
	}

	@Override
	public int delete(String table, String idField, List<String> idValues) throws Exception {
		int count = super.delete(table, idField, idValues);
		
		repo.clearSystemConfig();
		
		return count;
	}

	@Override
	public int delete(String table, String idField, List<String> idValues, String softField, String softFieldValue) throws Exception {
		int count = super.delete(table, idField, idValues, softField, softFieldValue);
		
		repo.clearSystemConfig();
		
		return count;
	}
}
